<template>
  <div :id="id"></div>
</template>

<script setup lang="tsx">
import { nextTick, onMounted, useId, watch } from 'vue';
import { createOlMap } from '@boeyo/hooks';
import { useInjectDisabled } from 'ant-design-vue/es/config-provider/DisabledContext';

const { useOl } = createOlMap();
const id = useId();

const lon = defineModel('lon', { type: Number, default: undefined });
const lat = defineModel('lat', { type: Number, default: undefined });

const disabled = useInjectDisabled();

const extent: [[number, number], [number, number]] = [
  [73.33, 3.51],
  [135.05, 53.33], // 右上角经度纬度转投影坐标
];

const { renderTile, renderFeature, removeFeature, animate } = useOl({
  target: id,
  tileUrl: VITE_MAP_URL,
  maxZoom: 14,
  zoom: 9,
  extent,
  olOption: {
    constrainResolution: true,
  },
  onClick({ lonLat }) {
    if (disabled.value) return;

    lon.value = parseFloat(lonLat[0].toFixed(4));
    lat.value = parseFloat(lonLat[1].toFixed(4));
    animate({
      center: lonLat,
    });
  },
});

watch(
  [lon, lat],
  () => {
    nextTick(() => {
      if (lon.value !== undefined && lat.value !== undefined) {
        removeFeature();
        renderFeature({
          lonLat: [lon.value, lat.value],
          style: {
            image: {
              src: '/static/map/marker-icon.png',
              scale: 0.5,
            },
          },
        });
      }
    });
  },
  { immediate: true },
);

onMounted(() => {
  renderTile();
  if (lon.value && lat.value) {
    animate({
      center: [lon.value, lat.value],
      duration: 1,
    });
  }
});
</script>
